// cloudfunctions/withdrawPoints/index.js
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        const {
            userId,
            userName,
            amount,
            cardId
        } = event

        if (!userId || !amount || !cardId) {
            return {
                success: false,
                message: '参数缺失'
            }
        }

        // 开启事务
        const transaction = await db.startTransaction()

        try {
            // 1. 查询用户积分
            const pointsRes = await transaction.collection('user_points').where({
                userId: userId
            }).get()
            const pointsData = pointsRes.data

            if (!pointsData || pointsData.points < amount) {
                await transaction.rollback()
                return {
                    success: false,
                    message: '积分不足'
                }
            }

            // 2. 查询银行卡信息
            const cardRes = await transaction.collection('user_bank_cards').doc(cardId).get()
            const cardData = cardRes.data

            if (!cardData || cardData.userId !== userId) {
                await transaction.rollback()
                return {
                    success: false,
                    message: '银行卡不存在或无权限'
                }
            }

            // 3. 计算提现金额 (10积分=1元)
            const money = (amount * 0.99 /100).toFixed(2)

            // 4. 生成提现记录
            const withdrawalId = `WD_${Date.now()}`
            const withdrawalRecord = {
                _id: withdrawalId,
                userId,
                userName,
                amount,
                money,
                bankCardId: cardId,
                cardHolder: cardData.cardHolder,
                bankName: cardData.bankName,
                bankNum: cardData.cardNumber,
                status: '1', // 1=未结算
                createTime: db.serverDate(),
                updateTime: db.serverDate(),
                remark: '用户申请提现'
            }

            // 5. 生成积分扣除记录
            const pointsRecord = {
                recordId: withdrawalId,
                type: 2,
                amount: amount,
                relatedWithdrawalId: withdrawalId,
                createTime: db.serverDate(),
                remark: `提现扣除积分(${amount})`
            }

            await transaction.collection('user_points').where({
                userId: userId
            }).update({
                data: {
                    frozenPoints: _.inc(amount), // 增加冻结积分
                    records: _.unshift(pointsRecord)
                }
            })

            // 7.2 保存提现记录
            await transaction.collection('points_withdrawal').add({
                data: withdrawalRecord
            })

            // 提交事务
            await transaction.commit()
            return {
                success: true,
                message: '提现申请已提交',
                withdrawalId
            }

        } catch (error) {
            await transaction.rollback()
            throw error
        }

    } catch (error) {
        console.error('提现失败:', error)
        return {
            success: false,
            message: error.message || '提现失败'
        }
    }
}